<template>
  <div id="register">
    <div class="register-title">
      <h1>后台管理</h1>
    </div>
    <div id="register-box">
      <div class="sub-title">注册</div>
      <div class="register-body">
        <form @submit.prevent="createUser">
          <input
            type="text"
            name="username"
            v-model="user.username"
            placeholder="用户名"
          />
          <input
            type="password"
            name="password"
            v-model="user.password"
            placeholder="密码"
          />
          <input
            type="password"
            name="comfirm"
            v-model="comfirmPassword"
            placeholder="确认密码"
          />
          <button>立即注册</button>
        </form>
        <span class="login"><a @click="goLogin">使用已有账号登录</a></span>
      </div>
    </div>
  </div>
</template>
<script>
import request from "../utils/request";
export default {
  data() {
    return {
      user: {
        username: "",
        password: "",
      },
      comfirmPassword: "",
    };
  },
  methods: {
    goLogin() {
      this.$router.push("/login");
    },
    createUser() {
      if (this.user.username) {
        if (this.user.password) {
          if (this.user.password === this.comfirmPassword) {
            request
              .post("user", {
                username: this.user.username,
                password: this.user.password,
              })
              .then((res) => {
                if (res.data.code === 20000) {
                  this.$message.success("注册成功");
                  this.$router.push("/login");
                } else {
                  console.log(res.data)
                  this.$message.error("服务器错误");
                }
              });
          } else {
            this.$message.error("请确保两次输入的密码相同");
          }
        } else {
          this.$message.error("请输入密码");
        }
      } else {
        this.$message.error("请输入用户名");
      }
    },
  },
};
</script>

<style lang="less" scoped>
#register{
  display: flex;
  justify-content: center;
  align-self: center;
  min-height: 100vh;
}
</style>